import { USER_LOGIN_SUCCESS, USER_RESET } from '../actions/constants'

import _ from 'lodash'

const initialState = {
  info: null,
  token: null,
  username: null,
  permissions: null,
  id: null,
  roles: null,
}

/**
 * 用于同步更新与用户登录状态相关的状态数据
 * state 更新前的旧状态
 * action 普通对象，描述如何更新状态，有 type 和 payload 属性
 * @return 返回更新后的状态
 */

export default (state = initialState, { type, payload }) => {
  // 对原 state 实行深拷贝
  const copy = _.cloneDeep(initialState)

  switch (type) {

  case USER_LOGIN_SUCCESS: // 登陆成功
    copy.info = payload.info
    copy.username = payload.username
    copy.token = payload.token
    copy.permissions = payload.permissions
    copy.id = payload.id
    copy.roles = payload.roles
    return copy

  case USER_RESET:
    copy.info = null,
    copy.username = null
    copy.token = null
    copy.permissions = null
    copy.id = null
    copy.roles = null
    return copy

  default:
    return state
  }
}
